package link.cocoon.sms.service.impl;

import com.aliyuncs.exceptions.ClientException;
import com.fasterxml.jackson.core.JsonProcessingException;
import javax.annotation.Resource;
import link.cocoon.sms.cache.SmsCacheService;
import link.cocoon.sms.service.SmsService;
import link.cocoon.sms.service.VerificationCodeService;
import link.cocoon.sms.util.VerificationCodeGenerator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * @author xce
 * @date 2020/3/19  16:39
 */
@Service
@Slf4j
public class VerificationCodeServiceImpl implements VerificationCodeService {

  @Resource
  private SmsCacheService smsCacheService;

  @Resource
  private SmsService smsService;


  @Override
  public void sendVerificationCode(String address) {
    String code = VerificationCodeGenerator.generate();
    try {
      log.info("发送目标:{},Code:{}", address, code);
      smsService.sendSmsCode(address, code);
      smsCacheService.put("phone",address, code);
    } catch (ClientException | JsonProcessingException e) {
      e.printStackTrace();
      log.error("短信验证码发送失败 Message：{}" + e.getMessage());
    }
  }

  @Override
  public boolean verify(String address, String userCode) {
    String code = smsCacheService.get("phone",address);
    return StringUtils.equals(userCode, code);
  }
}
